<template>
  <v-layout>
    <template #header>
      <el-date-picker
        v-model="tableQuery.timeRange"
        type="datetimerange"
        range-separator="-"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD HH:mm:ss"
        @change="getDiviverList"
      />
    </template>
    <v-table
      url="/divideOrder/getDivideOrderList"
      ref="tableRef"
      :query="tableQuery"
    >
      <v-column auto prop="scName" label="学校名称"></v-column>
      <v-column auto prop="code" label="分单编号"></v-column>
      <v-column auto prop="dtBegin" label="配送开始时间"></v-column>
      <v-column auto prop="dtEnd" label="配送结束时间"></v-column>
      <v-column auto label="操作">
        <template #default="{ row }">
          <el-button size="small" @click="toOp(row)">详情</el-button>
        </template>
      </v-column>
    </v-table>
    <v-dialog
      v-model="detailVisible"
      title="详情"
      width="1000px"
      @printbtn="printlist"
      :showExport="showExport"
      confirmText="导出"
      @confirm="exportbtn"
      :printhide="printhide"
    >
      <el-table :data="detailList" style="width: 100%" height="550">
        <el-table-column prop="name" label="商品名称" width="150" />
        <el-table-column prop="format" label="规格" width="150" />
        <el-table-column prop="cunit" label="单位" width="120" />
        <el-table-column prop="price" label="价格" width="150" />
        <el-table-column prop="num" label="数量" width="150" />
        <el-table-column prop="vendorid" label="供应商" width="120" />
        <el-table-column prop="dtBegin" label="配送开始时间" width="120" />
        <el-table-column prop="dtEnd" label="配送结束时间" width="120" />
      </el-table>

      <div id="printDiv">
        <div
          style="page-break-after: always"
          v-for="(p, pIndex) in arrdata"
          :key="pIndex"
        >
          <h3 style="text-align: center">{{ tableData.scName }}食材发货单</h3>
          <div
            style="
              display: flex;
              justify-content: space-between;
              margin-bottom: 5px;
            "
          >
            <div>订单号:{{ tableData.code }}</div>
            <div>供应商:{{ arrdata[0][0].vendorid}}</div>
            <div>页码:{{ pIndex + 1 }}/{{ arrdata.length }}</div>
          </div>
          <div
            style="
              display: flex;
              justify-content: space-between;
              margin-bottom: 5px;
            "
          >
            <div>配送开始时间:{{ tableData.dtBegin }}</div>
            <div>配送结束时间:{{ tableData.dtEnd }}</div>
          </div>
          <table
            border="1"
            style="border-collapse: collapse; text-align: center"
          >
            <thead>
              <tr>
                <th class="tablethTr">食材类别:</th>
                <th class="tablethTr">
                  {{ p[0].cclass }}
                </th>
                <th class="tablethTr">打单时间:</th>
                <th class="tablethTr" colspan="2">
                  {{ dayjs().format("YYYY-MM-DD HH:mm:ss") }}
                </th>
                <th class="tablethTr">收货时间:</th>
                <th class="tablethTr">
                  {{ dayjs().format("YYYY-MM-DD HH:mm:ss") }}
                </th>
              </tr>
              <tr>
                <th class="tablethTr">序号</th>
                <th class="tablethTr">食材名称</th>
                <th class="tablethTr">规格型号</th>
                <th class="tablethTr">数量</th>
                <th class="tablethTr">单价</th>
                <th class="tablethTr" colspan="2">备注</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(it, index) in p" :key="index">
                <td class="tablethTr">
                  {{ index + 1 }}
                </td>
                <td class="tablethTr">
                  {{ it.name }}
                </td>
                <td class="tablethTr">
                  {{ it.format }}
                </td>
                <td class="tablethTr">
                  {{ it.num }}
                </td>
                <td class="tablethTr">
                  {{ it.price }}
                </td>
                <td class="tablethTr" colspan="2">
                  
                </td>
              </tr>
            </tbody>
            <tfoot style="text-align: left">
              <tr>
                <td class="tablethTr" colspan="4">
                  本页小计:￥{{ p[0].oneTableSumPrice }}元（大写:）{{
                    capitalAmount(p[0].oneTableSumPrice)
                  }}
                </td>
                <td class="tablethTr" colspan="3">
                  总计:￥{{ sumPrice.toFixed(1) }}元（大写:）{{ capitalAmount(sumPrice) }}
                </td>
              </tr>
              <tr style="text-align: center">
                <td>采购人:</td>
                <td></td>
                <td>送货人:</td>
                <td colspan="2"></td>
                <td>验收人:</td>
                <td></td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
    </v-dialog>
  </v-layout>
</template>

<script setup lang="ts">
import { useTable } from "@/components/table/useTable";
import { useUserStore } from "@/stores/user";
import { queryDivideOrderList, printinformation } from "@/api/user";
import type { divideDetailData } from "@/api/user/model";
import { reactive, ref } from "vue";
import { exportExcelMethod } from "@/utils/excel";
import { capitalAmount ,dateFormat} from "@/utils";
import dayjs from "dayjs";

const { tableRef, getSelectionRows, reload } = useTable();

interface Data {
  id: string;
  scName: string;
  shopId: string;
  code: string;
  status: string;
  fdUser: string;
  createTime: string;
}

interface tableDatatype {
  code: string;
  dtBegin: string;
  dtEnd: string;
  scName: string;
}
let arrdata = ref([]); //定义数组，并初始化

const printhide = ref(false);
const { tznUser } = useUserStore();
const tableQuery = reactive({
  timeRange: "",
  status: 1,
  beginTime: "",
  endTime: "",
  id: tznUser.id,
  type: tznUser.type,
});

const tableData = ref<tableDatatype>({
  code: "",
  dtBegin: "",
  dtEnd: "",
  scName: "",
});

const sumPrice = ref<number>(0);
const getDiviverList = () => {
  tableQuery.beginTime = tableQuery.timeRange[0];
  tableQuery.endTime = tableQuery.timeRange[1];
  reload();
};
const detailVisible = ref(false);
const code = reactive({
  code: "",
});

const exportcode = reactive({
  code: "",
});
const detailList = ref<divideDetailData[]>([]);
const toOp = (row: Data) => {
  detailVisible.value = true;
  code.code = row.code;
  exportcode.code = row.code;
  queryDivideOrderList(code).then((data) => {
    detailList.value = data;
  });
  printhide.value = true;

  printinformation(code).then((data) => {
    //二维数组遍历
    arrdata.value = [];
    tableData.value.code = data.code;
    tableData.value.dtBegin = dateFormat(data.dtBegin);
    tableData.value.dtEnd = dateFormat(data.dtEnd);
    tableData.value.scName = data.scName;
    for (let i in data.list) {
      let shouldAddnum = data.list[i].length % 7;

      if (shouldAddnum != 0) {
        for (let j = shouldAddnum; j < 7; j++) {
          data.list[i].push({
            name: "",
            cunit: "",
            format: "",
            cclass: "",
            num: "",
            price: "",
            vendorid: "",
          });
        }
      }
    }

    let list = [];
    data.list.map((item, index) => {
      if (item.length > 7) {
        let arr = changeArrGroup(item, 7);
        for (let i in arr) {
          let tableitem = [];
          let sum = arr[i].reduce(
            (sum, current) => Number(sum) + Number(current.price),
            0
          );
          arr[i][0].oneTableSumPrice = sum;
          tableitem = tableitem.concat(arr[i]);
          sumPrice.value += Number(sum);
          list.push(tableitem);
        }
      } else {
        let tableitem = [];
        let sum = item.reduce(
          (sum, current) => Number(sum) + Number(current.price),
          0
        );
        item[0].oneTableSumPrice = sum;
        sumPrice.value += Number(sum);
        tableitem = tableitem.concat(item);

        list.push(tableitem);
      }
    });

    arrdata.value = list;
    console.log(arrdata)
  });
};
//打印
const showExport = ref(true);
const printlist = () => {
  printhide.value = true;
};

const changeArrGroup = (arr, newArrLength) => {
  let changeIndex = 0;
  let secondArr = [];
  while (changeIndex < arr.length) {
    secondArr.push(arr.slice(changeIndex, (changeIndex += newArrLength)));
  }
  return secondArr;
};
//导出
const exportbtn = () => {
  const url = `/assist/export/exportDividerOrderList?code=${code.code}`;
  const myObj = {
    method: "get",
    url: url,
  };
  exportExcelMethod(myObj);
};
</script>
<style lang="scss" scoped>
@page {
  size: auto;
  margin: 5mm;
}

table {
  border-collapse: collapse;
  border: 1px solid gray;
  width: 100%;
  font-size: 0.28rem;
  tr {
    width: 100%;
    td {
      text-align: center;
    }
  }
}
.tablethTr {
  text-align: center;
  border-bottom: 1px solid gray;
  border-right: 1px solid gray;
}
</style>
